<template>
  <div class="home">
    <div class="body">
        <div class="title">
            <div style="float:left">成品入库</div>
            <div style="float:right"><el-button
                    type="primary"
                    class="button orgbtn"
                    @click="checkWeight"
                    >校&nbsp;称</el-button></div>
            <div style="float:right"><el-button
                    type="primary"
                    class="button orgbtn"
                    style="margin-right:10px;"
                    @click="printProduct"
                    >打印清单</el-button></div>
        </div>
        <el-row :gutter="20">
            <el-col :span="13">
                <div class="table-w">
                    <div class="title">料框信息</div>
                    <div class="block-w">
                        <div class="block">
                            <div class="line">
                                <div class="row">
                                    <div class="tit">料框编号：</div>
                                    <div class="des">
                                        {{stackLocation.RFID}}
                                        <input v-model="stackLocation.RFID" ref="RFID" type="text" @keyup.enter="getStackInfo"/>
                                    </div>
                                    <el-button
                                            type="primary"
                                            class="button"
                                            style="margin-left:10px;margin-top: 7px;"
                                            @click="getFocus(1)"
                                        >扫描料框</el-button>
                                </div>
                                <div class="row">
                                    <div class="tit">料框自重：</div>
                                    <div class="des">{{stackLocation.StackWeight}}千克</div>
                                </div>
                            </div>
                            <div class="line">
                                <div class="row"> 
                                </div>
                                <div class="row">
                                    <div class="tit">当前重量：</div>
                                    <div class="des">{{stackLocation.NowWeight}}千克</div>
                                </div>
                            </div>
                            <el-table
                                :data="finishedInStockList"
                                :row-style="tableRowStyle"
                                :header-cell-style="tableHeaderColor"
                                highlight-current-row
                                style="width: 100%;font-size:16px;"
                                height="11rem"
                                >
                                <el-table-column label="序号" width="60" align="center">
                                    <template slot-scope="scope">{{scope.$index + 1}}</template>
                                </el-table-column>
                                <el-table-column prop="MaterielName" label="名称" align="center"></el-table-column>
                                <el-table-column prop="SpecConfigName" label="尺码/型号" width="160" align="center"></el-table-column>
                                <el-table-column prop="ColorConfigName" label="颜色/规格" width="120" align="center"></el-table-column>
                                <el-table-column prop="StyleName" label="款式" width="120" align="center"></el-table-column>
                                <el-table-column prop="StockCount" label="数量" width="120" align="center"></el-table-column>
                                <el-table-column prop="TotalWeight" label="重量(克)" width="140" align="center"></el-table-column>
                                <el-table-column prop="InventoryTime" label="时间" width="160" align="center">
                                    <template slot-scope="scope">
                                    {{$moment(scope.row.InventoryTime).format('YYYY-MM-DD HH:mm')}}
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-pagination
                                background
                                layout="prev, pager, next"
                                :total="totalCount"
                                :current-page.sync="currentPage"
                                :page-size="pageSize"
                                @current-change="changePage()"
                                style="margin:20px 0;"
                            ></el-pagination>
                        </div>
                    </div>
                </div>
            </el-col>
            <el-col :span="11">
                <div class="table-w">
                    <div class="block-w">
                        <div class="block">
                            <table>
                                <tr>
                                    <th>款式-制令：</th>
                                    <td colspan="3">
                                        <span v-if="poInfo!=null">{{poInfo.StyleName}}</span>
                                        <span v-if="taskCodeInfo.TaskCode!=''"> - {{taskCodeInfo.TaskCode}}</span>
                                        <span v-else></span>
                                        <el-button
                                            type="primary"
                                            class="button"
                                            v-bind:class="{'active':taskCodeInfo.TaskCode!=''}"
                                            @click="showTaskList"
                                        >选择</el-button></td>
                                </tr>
                                <tr>
                                    <th>型号：</th>
                                    <td colspan="3">
                                        <a @click="selectColor(index)" v-bind:class="{'active':selColorConfigIndex==index}" v-for="(item,index) in ColorConfigNames" :key="index">{{item.ColorConfigName}}</a>
                                    </td>
                                </tr>
                                <tr>
                                    <th>规格：</th>
                                    <td colspan="3">
                                        <a @click="selectSpec(index)" v-bind:class="{'active':selSpecConfigIndex==index}" v-for="(item,index) in SpecConfigNames" :key="index">{{item.SpecConfigName}}</a>
                                    </td>
                                </tr>
                                <tr>
                                    <th>产线：</th>
                                    <td colspan="3">
                                        <a @click="selectProd(index)" v-bind:class="{'active':selProductLineIndex==index}" v-for="(item,index) in ProductLines" :key="index">{{item.LineName}}</a>
                                        <input type="text" v-model="productLineID" ref="productLineID"/>
                                    </td>
                                </tr>
                                <tr style="height:4rem;">
                                    <th style="padding-top:1.5rem;">入库数量：</th>
                                    <td colspan="3">
                                        <div @click="sumTaskCount(-100)" class="btn">-100</div>
                                        <div @click="sumTaskCount(-50)" class="btn">-50</div>
                                        <div @click="sumTaskCount(-10)" class="btn">-10</div>
                                        <div @click="sumTaskCount(-1)" class="btn">-1</div>
                                        <input class="num" type="text" v-model="taskCount"/>
                                        <div @click="sumTaskCount(+1)" class="btn">+1</div>
                                        <div @click="sumTaskCount(+10)" class="btn">+10</div>
                                        <div @click="sumTaskCount(+50)" class="btn">+50</div>
                                        <div @click="sumTaskCount(+100)" class="btn">+100</div>
                                    </td>
                                </tr>
                                <tr style="height:4rem;">
                                    <td colspan="4" style="text-align:center;">
                                        <el-button
                                            type="primary"
                                            class="button"
                                            style="margin-left:10px"
                                            @click="dataInStock()"
                                        >入库</el-button>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>
    
    <!-- 选择制令弹出框 -->
    <div class="dialogBox-w" v-show="dialogTaskShow">
      <div class="dialogBox" >
        <div>
            <div class="title">合同信息</div>
            <div class="close">
                <div class="el-icon-circle-close icon" @click="dialogTaskShow = false"/>
            </div>
        </div>
        <div class="block-w">
          <div class="block" v-for="(item,index) in poList" :key="index" @click="selPO(index)">
            <div class="block-top">合同号：{{item.POCode}}</div>
            <div class="block-bot">
              <div>批次：{{item.SaleBatchNo}}</div>
              <div>客户名：{{item.CustomerName}}</div>
              <div>款式：{{item.StyleName}}</div>
              <div>合同总数：{{item.TotalCount}}</div>
              <div>合同日期：{{item.PODate}}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 选择制令弹出框 -->
    <div class="dialogBox-w" v-show="dialogProductShow">
      <div class="dialogBox" style="width:55%">
        <div>
            <div class="title">制令信息</div>
            <div class="close">
                <div class="el-icon-circle-close icon" @click="dialogProductShow=false"/>
            </div>
        </div>
        <div class="block-w" style="width:20rem;overflow-x:hidden;">
          <div class="block" style="width:6rem;height:3.5rem;" v-for="(item,index) in taskCodeList" :key="index" @click="selTaskCode(index)">
            <div class="block-top">制令号：{{item.TaskCode}}</div>
            <div class="block-bot">
              <div>工艺路线：{{item.ProcessLineName}}</div>
              <div>日期：{{item.IssueDate}}</div>
              <div>制令数：{{item.TaskCount}}</div>
              <div>入库数：{{item.CompletCount}}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 校称 -->
    <div class="menuModalBox-w" v-if="swipeCardShow">
      <div class="menuModalBox">
        <div class="close">
          <div class="el-icon-circle-close icon" @click="handleClose()" />
        </div>
        <Validity :p1="type" :p2="materiel"></Validity>
      </div>
    </div>
  </div>
</template>
<script>
import Mixin from '@/components/mixin' // 混入
import Validity from '@/view/tool/validity'
import {GetStackByBarCode, GetProductTaskListByFilter, GetSaleContractListByLineID, SaveFinishedInStock, GetFinishedInStockByOperID,
GetMaterielsDetailByID, GetPrintInStockByOperID, GetProductLineByOrgID} from '@/api/prison' // 接口
export default {
  name: 'productfinished',
  data () {
    return {
      dialogTaskShow: false, // 是否显示弹出框
      currentPage: 1, // 左侧列表当前页面
      pageSize: 14, // 当前显示的行数
      totalCount: 0, // 列表行总数
      stackLocation: {
        RFID: '',
        StackWeight: '0.00',
        NowWeight: '0.00',
        MaterielWeightUp: 0, // 最大重量 毛重
        CardID: ''
      }, // 垛架信息
      // 合同列表
      poList: [],
      taskCodeList: [], // 制令号列表
      dialogProductShow: false, // 显示制令列表
      taskCodeInfo: {
        TaskCode: '',
        ColorConfigName: '',
        SpecConfigName: '',
        ColorConfigNames: '',
        SpecConfigNames: '',
        TaskCount: 1
      },
      ColorConfigNames: [],
      SpecConfigNames: [],
      selColorConfigIndex: -1,
      selSpecConfigIndex: -1,
      poInfo: null,
      taskCount: 1,
      ProductLines: [],
      selProductLineIndex: -1,
      productLineID: '',
      finishedInStockList: [],
      allConfigCode: [],
      swipeCardShow: false,
      materiel: '',
      type: 'P'
    }
  },
  computed: {},
  components: {
    Validity
  },
  mixins: [Mixin],
  methods: {
    // 修改table tr行的背景色
    tableRowStyle ({ row, rowIndex }) {
      return {
        backgroundColor: 'rgb(0, 63, 140)',
        color: '#fff',
        fontWeight: 'bold',
        height: '0.7rem',
        fontSize: '15px'
      }
    },
    // 修改table header的背景色
    tableHeaderColor ({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background-color: rgb(0, 63, 140);color: #fff;font-weight: bold;height:0.7rem;font-size:15px'
      }
    },
    // 选择制令列表
    showTaskList () {
      let vm = this
      vm.getProductTaskList()
      vm.dialogTaskShow = true
    },
    // 分页显示
    changePage () {
      let vm = this
      vm.getFinishedInStockList()
    },
    // 需要扫码获取料框信息
    getStackInfo () {
      let vm = this
      if (vm.stackLocation.RFID === '') {
        vm.$message('请扫描料框')
        return
      }
      let params = new FormData()
      params.append('RFID', vm.stackLocation.RFID)
      GetStackByBarCode(params).then((response) => {
        if (response.data.result &&
            response.data.data != null &&
            response.data.data.length > 0) {
          var info = response.data.data[0]
          vm.stackLocation.RFID = info.RFID
          vm.stackLocation.CardID = info.CardID
          vm.stackLocation.StackWeight = info.StackWeight
          vm.stackLocation.NowWeight = (info.TotalWeight === '' ? '0.00' : info.TotalWeight)
          vm.stackLocation.MaterielWeightUp = info.MaterielWeightUp
        } else {
          vm.$message('料框信息不存在')
          vm.stackLocation.RFID = ''
          vm.stackLocation.StackWeight = '0.00'
          vm.stackLocation.NowWeight = '0.00'
          vm.stackLocation.MaterielWeightUp = 0
          vm.stackLocation.CardID = ''
        }
        vm.getFinishedInStockList()
      })
    },
    // 根据产品编号获得制令列表
    getProductTaskList () {
      let vm = this
      let params = new FormData()
      params.append('LineFlnkID', localStorage.getItem('OrgID'))
      GetSaleContractListByLineID(params).then((response) => {
        if (response.data.result) {
          if (
              response.data.data &&
              response.data.data.length &&
              response.data.data.length > 0
            ) {
            var list = response.data.data
            list.forEach(element => {
              element.isSel = 0
            })
            vm.poList = list
          } else {
            vm.$message('暂无合同信息')
          }
        } else {
          vm.$message(response.data.error)
        }
      })
    },
    // 选择合同
    selPO (index) {
      let vm = this
      vm.poList[index].isSel = 1
      vm.poInfo = vm.poList[index]
      let params = new FormData()
      params.append('HTCode', vm.poList[index].POCode)
      params.append('OrderOuterCode', vm.poList[index].OrderOuterCode)
      params.append('StyleName', vm.poList[index].StyleName)
      GetProductTaskListByFilter(params).then((response) => {
        if (response.data.result) {
          if (
              response.data.data &&
              response.data.data.length &&
              response.data.data.length > 0
            ) {
            var list = response.data.data
            vm.taskCodeList = list
            if (response.data.data.length > 1) {
              list.forEach(element => {
                element.isSel = 0
              })
              vm.dialogTaskShow = false
              vm.dialogProductShow = true
            } else {
              vm.taskCodeInfo = vm.taskCodeList[0]
              vm.selColorConfigName = vm.taskCodeInfo.ColorConfigName
              vm.selSpecConfigName = vm.taskCodeInfo.SpecConfigName
              vm.dialogTaskShow = false
              vm.dialogProductShow = false
            }
          } else {
            vm.$message('暂无制令信息')
            vm.taskCodeInfo.TaskCode = ''
            vm.dialogTaskShow = false
            vm.dialogProductShow = false
          }
            // 根据款式编号获取款式信息
          params = new FormData()
          params.append('MaterielsFlnkID', vm.poList[index].StyleFlnkID)
          GetMaterielsDetailByID(params).then((response) => {
            vm.ColorConfigNames = response.data.data.colorConfig
            vm.SpecConfigNames = response.data.data.specConfig
            vm.allConfigCode = response.data.data.allConfig
            vm.selColorConfigIndex = -1
            vm.selSpecConfigIndex = -1
            vm.$nextTick(() => {
              vm.$refs.productLineID.focus()
            })
          })
        } else {
          vm.$message(response.data.error)
        }
      })
    },
    // 选择的第几个制令信息
    selTaskCode (index) {
      let vm = this
      vm.taskCodeInfo = vm.taskCodeList[index]
      vm.selColorConfigName = vm.taskCodeInfo.ColorConfigName
      vm.selSpecConfigName = vm.taskCodeInfo.SpecConfigName
      vm.dialogTaskShow = false
      vm.dialogProductShow = false
    },
    // 型号切换
    selectColor (index) {
      let vm = this
      vm.selColorConfigIndex = index
      vm.$nextTick(() => {
        vm.$refs.productLineID.focus()
      })
    },
    // 规格切换
    selectSpec (index) {
      let vm = this
      vm.selSpecConfigIndex = index
      vm.$nextTick(() => {
        vm.$refs.productLineID.focus()
      })
    },
    // 产线切换
    selectProd (index) {
      let vm = this
      vm.selProductLineIndex = index
      vm.productLineID = vm.ProductLines[index].FlnkID
      vm.$nextTick(() => {
        vm.$refs.productLineID.focus()
      })
    },
    // 扫码获取产线
    // getProductLineID () {
    //   let vm = this
    //   vm.productLineID
    // },
    // 增删总数
    sumTaskCount (no) {
      let vm = this
      try {
        vm.taskCount = parseInt(vm.taskCount) + parseInt(no)
        vm.taskCount = vm.taskCount < 0 ? 0 : vm.taskCount
      } catch (ex) {
        vm.$message('请输入整型数据')
      }
    },
    // 入库
    dataInStock () {
      let vm = this
      if (vm.stackLocation.RFID === '') {
        vm.$message('请扫描料框')
        return
      }
    //   if (vm.taskCodeInfo.TaskCode === '') {
    //     vm.$message('请选择制令')
    //     return
    //   }
      if (vm.selColorConfigIndex === -1) {
        vm.$message('请选择型号')
        return
      }
      if (vm.selSpecConfigIndex === -1) {
        vm.$message('请选择规格')
        return
      }
      if (vm.productLineID === '') {
        vm.$message('请选择产线或扫码')
        return
      }
      if (vm.taskCount === 0 || vm.taskCount === '0') {
        vm.$message('请填写入库数')
        return
      }
      var wareHouse = localStorage.getItem('WarehouseFlnkID')
      if (wareHouse !== '') {
        wareHouse = JSON.parse(wareHouse)
      }
      wareHouse.forEach(element => {
        if (element.type === 'P' || element.type === 'p') {
          this.wareID = element.WarehouseFlnkID
        }
      })
      if (this.wareID === '') {
        vm.$message('登录信息出错')
        return
      }
      let params = new FormData()
      params.append('BarCode', vm.stackLocation.RFID)
      params.append('WarehouseFlnkID', this.wareID)
      params.append('CustomerFlnkID', vm.poInfo.CustomFlnkID)
      params.append('OrderOuterCode', vm.poInfo.OrderOuterCode)
      params.append('StyleFlnkID', vm.poInfo.StyleFlnkID)
      params.append('ColorConfigCode', vm.ColorConfigNames[vm.selColorConfigIndex].ColorConfigCode)
      params.append('SpecConfigCode', vm.SpecConfigNames[vm.selSpecConfigIndex].SpecConfigCode)
      params.append('StockCount', vm.taskCount)
      params.append('ProductLineFlnkID', vm.productLineID)
      params.append('OrderBatch', vm.poInfo.SaleBatchNo)
      params.append('PlanID', vm.taskCodeInfo.TaskCode)
      params.append('OperFlnkID', localStorage.getItem('UserFlnkID'))
      SaveFinishedInStock(params).then((response) => {
        vm.$message(response.data.error)
        if (response.data.result) {
          vm.getFinishedInStockList()
          vm.getStackInfo()
        }
      })
    },
    // 获取组信息
    getProductLine () {
      let vm = this
      let params = new FormData()
      params.append('OrgID', localStorage.getItem('OrgID'))
      GetProductLineByOrgID(params).then((response) => {
        if (response.data.result) {
          vm.ProductLines = response.data.data
          vm.selProductLineIndex = -1
        } else {
          vm.$message(response.data.error)
        }
      })
    },
    // 成品入库列表
    getFinishedInStockList () {
      let vm = this
      let params = new FormData()
      params.append('OperFlnkID', localStorage.getItem('UserFlnkID'))
      params.append('BarCode', vm.stackLocation.RFID)
      params.append('PageIndex', vm.currentPage)
      params.append('PageSize', vm.pageSize)
      GetFinishedInStockByOperID(params).then((response) => {
        if (response.data.result) {
          vm.finishedInStockList = response.data.data
          vm.totalCount = response.data.count
        } else {
          vm.$message(response.data.error)
        }
      })
    },
    // 校称
    checkWeight () {
      let vm = this
      if (vm.selColorConfigIndex === -1) {
        vm.$message('请选择型号')
        return
      }
      if (vm.selSpecConfigIndex === -1) {
        vm.$message('请选择规格')
        return
      }
      // 根据选择型号规格获取FlnkID
      vm.allConfigCode.forEach(element => {
        if (element.ColorConfigCode === vm.ColorConfigNames[vm.selColorConfigIndex].ColorConfigCode &&
            element.SpecConfigCode === vm.SpecConfigNames[vm.selSpecConfigIndex].SpecConfigCode
          ) {
          this.flnkID = element.FlnkID
          vm.materiel = this.flnkID
        }
      })
      if (this.flnkID !== undefined && this.flnkID !== null) {
        // vm.$router.push({path: '/tool/validity', query: {flnkID: this.flnkID}})
        vm.swipeCardShow = true
      } else {
        vm.$message('没有符合的型号和规格')
      }
    },
    handleClose () {
      this.swipeCardShow = false
      if (this.type && this.materiel) {
        // this.getInfo()
      }
    },
    // 打印清单数据
    printProduct () {
      let vm = this
      if (vm.stackLocation.RFID === '') {
        vm.$message('请扫描料框')
      } else {
        let params = new FormData()
        params.append('OperFlnkID', localStorage.getItem('UserFlnkID'))
        params.append('BarCode', vm.stackLocation.RFID)
        GetPrintInStockByOperID(params).then((response) => {
          if (response.data.result) {
            var info = response.data.data
            let map = new Map()
            info.filter(ele => {
              if (!map.has(ele.CustomerName)) {
                map.set(ele.CustomerName, ele.CustomerName)
              }
            })
            var allTemp = []
            map.forEach(key => {
              var temp = info.filter(e1 => e1.CustomerName === key)
              var totalWeight = 0.0
              temp.forEach(e2 => {
                totalWeight += parseFloat(e2.TotalWeight)
              })

              allTemp.push({
                CompanyName: temp[0].CustomerName,
                BarCode: vm.stackLocation.RFID + '',
                CardID: vm.stackLocation.CardID + '',
                OrgNames: vm.getLocalStorage('OrgNames').replace(/监区/, '车间'),
                NowDate: vm.$moment(temp[0].NowDate).format('YYYY-MM-DD'),
                TotalWeight: totalWeight,
                Detail: temp
              })
            })
            if (vm.isAndroid()) {
              window.android.print('PK', JSON.stringify(allTemp))
            } else {
              vm.$message(JSON.stringify(allTemp))
            }
          } else {
            vm.$message(response.data.error)
          }
        })
      }
    },
    // 获取焦点
    getFocus (index) {
      let vm = this
      if (index === 1) {
        vm.stackLocation.RFID = ''
        vm.$nextTick(() => {
          vm.$refs.RFID.focus()
        })
      } else {
        vm.$nextTick(() => {
          vm.$refs.productLineID.focus()
        })
      }
    }
  },
  watch: {},
  mounted () {
    let vm = this
    vm.$nextTick(() => {
      vm.$refs.RFID.focus()
    })
    // vm.getProductTaskList()
    vm.getProductLine()
    // alert(vm.$route.query.type)
    if (vm.$route.query.type && vm.$route.query.materiel) {
      vm.type = vm.$route.query.type
      vm.materiel = vm.$route.query.materiel
    }
  },
  beforeDestroy: function () {}
}
</script>
<style lang="scss" scoped>
@import "~@/css/lcheck/productfinished.scss";
</style>
<style lang="scss">
.el-table::before {
  height: 0px;
}
</style>